package com.hc.action;

import com.hc.domain.Account;
import com.hc.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountActionImpl implements AccountAction {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void reduceMoney(BusinessActionContext context, int accountId,double amount) {
        Account account = accountMapper.findAccountById(accountId);
        if (account.getMoney() < amount) {
            throw new RuntimeException("余额不⾜");
        }
        System.out.println("account的try⽅法执⾏了");
        accountMapper.reduceMoney(amount, accountId);
    }

    @Override
    public void commit(BusinessActionContext context) {
        System.out.println("account的commit⽅法执⾏了");
        int accountId = context.getActionContext("accountId", Integer.class).intValue();
        double amount = context.getActionContext("amount", Double.class).doubleValue();
        accountMapper.commitReduce(amount, accountId);
    }

    @Override
    public void rollback(BusinessActionContext context) {
        System.out.println("account的rollback⽅法执⾏了");
        int accountId = context.getActionContext("accountId", Integer.class).intValue();
        double amount = context.getActionContext("amount", Double.class).doubleValue();
        accountMapper.cancelMoney(amount, accountId);
    }
}